import { isPlainObject } from './util'

function normalizeHeaderName(headers: any, ...normalizedNames: string[]) {
  if (!headers) {
    return
  }
  Object.keys(headers).forEach(name => {
    const normalizedName = normalizedNames.find(x => x.toUpperCase() === name.toUpperCase())
    if (!(normalizedName && name !== normalizedName)) {
      return
    }
    headers[normalizedName] = headers[name]
    delete headers[name]
  })
}

export function processHeaders(headers: any, data: any): any {
  normalizeHeaderName(headers, 'Content-Type', 'Accept')

  if (isPlainObject(data)) {
    if (headers) {
      if (!headers['Content-Type']) {
        headers['Content-Type'] = 'application/json;charset=utf-8'
      }
    }
  }

  return headers
}

export function parseHeaders(headers: string): any {
  let parsed = Object.create(null)

  if (!headers) {
    return parsed
  }

  headers.split('\r\n').forEach(line => {
    let [name, value] = line.split(':')
    name = name.trim().toLowerCase()
    if (!name) {
      return
    }
    if (value) {
      value = value.trim()
    }
    parsed[name] = value
  })

  return parsed
}
